package com.xiaoyu.tool.controller.client.wx.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoyu.tool.constant.MenuJsonKey;
import com.xiaoyu.tool.enums.CommentEnum;
import com.xiaoyu.tool.enums.ResultEnum;
import com.xiaoyu.tool.response.ResultResponse;
import com.xiaoyu.tool.utils.JsonValidator;
import com.xiaoyu.tool.utils.ResultResponseUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.menu.WxMpMenu;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaoyu
 * 公众号菜单操作  menus 数据案例查看notice.md
 */
@RestController
@RequestMapping(value = "/menus")
@Slf4j
public class WxMenusController {

    private final WxMpService wxMpService;

    public WxMenusController(WxMpService wxMpService) {
        this.wxMpService = wxMpService;
    }

    /**
     * 自定义菜单获取
     * */
    @ApiOperation("自定义菜单获取")
    @GetMapping
    public ResultResponse menuGet(){
        WxMpMenu wxMenu = null;
        try {
            wxMenu = wxMpService.getMenuService().menuGet();
        } catch (WxErrorException e) {
            log.error("获取菜单失败:{}",e.getMessage());
            return ResultResponseUtil.error(ResultEnum.USER_ERROR.getCode(),"获取失败");
        }
        return ResultResponseUtil.success(wxMenu);
    }


    /**
     * 创建菜单
     * */
    @ApiOperation("创建菜单")
    @PostMapping
    public ResultResponse menus(@RequestParam("menus") String menus){
        WxMenu wxMenu = new WxMenu();
        List<WxMenuButton> buttons = new ArrayList();
        //一级菜单按钮
        WxMenuButton buttonsFirst = new WxMenuButton();
        WxMenuButton buttonsSecond = new WxMenuButton();
        WxMenuButton buttonsThird = new WxMenuButton();
        //二级菜单buttonsFirst
        List<WxMenuButton> subButtonFirst = new ArrayList();
        List<WxMenuButton> subButtonSecond = new ArrayList();
        List<WxMenuButton> subButtonThird = new ArrayList();
        if (!JsonValidator.validate(menus)){
            return ResultResponseUtil.error(ResultEnum.PARAM_ERROR.getCode(),"菜单数据格式错误");
        }
        //去空格
        menus = menus.replace(" ","");
        JSONObject jsonObject = JSON.parseObject(menus);
        String button = jsonObject.getString(MenuJsonKey.WX_BUTTON);
        JSONArray objects = JSON.parseArray(button);
        if (objects.size() > CommentEnum.THREE.getCode()){
            return ResultResponseUtil.error(ResultEnum.PARAM_ERROR.getCode(),"一级菜单数量超过标准");
        }
        for (int index = CommentEnum.ZERO.getCode() ; index < objects.size() ; index++) {
            boolean menusJson = true;
            if (index == CommentEnum.ZERO.getCode()){
                menusJson = createMenus(buttonsFirst, objects, index, subButtonFirst);
            }else if (index == CommentEnum.ONE.getCode()){
                menusJson = createMenus(buttonsSecond,objects,index,subButtonSecond);
            }else if (index == CommentEnum.TWO.getCode()){
                menusJson = createMenus(buttonsThird,objects,index,subButtonThird);
            }
            if (!menusJson){
                return ResultResponseUtil.error(ResultEnum.PARAM_ERROR.getCode(),objects.getJSONObject(index).getString(MenuJsonKey.BUTTON_NAME) + ": 二级菜单超过标准或type类型与key/url参数不一致");
            }
        }
        //封装完菜单
        buttons.add(buttonsFirst);
        buttons.add(buttonsSecond);
        buttons.add(buttonsThird);
        wxMenu.setButtons(buttons);
        //开始生成菜单
        try {
            wxMpService.getMenuService().menuCreate(wxMenu);
            log.info("创建菜单成功:{}",wxMenu);
        } catch (Exception e) {
            log.error("创建菜单失败:{}",e.getMessage());
            return ResultResponseUtil.error(ResultEnum.USER_ERROR.getCode(),"创建失败");
        }
        return ResultResponseUtil.success();
    }


    /**
     * 一级菜单封装
     * */
    private boolean createMenus(WxMenuButton stairButton,
                                JSONArray objects,
                                Integer index,
                                List<WxMenuButton> subButtonList){
        //一级菜单按钮
        JSONObject object = objects.getJSONObject(index);
        String type = object.getString(MenuJsonKey.BUTTON_TYPE);
        String name = object.getString(MenuJsonKey.BUTTON_NAME);
        String keyOrUrl = "";
        if (type.equals(WxConsts.MenuButtonType.CLICK)) {
            keyOrUrl = object.getString(MenuJsonKey.BUTTON_KEY);
            if (StringUtils.isEmpty(keyOrUrl)){
                return false;
            }
            stairButton.setKey(keyOrUrl);
        }else if (type.equals(WxConsts.MenuButtonType.VIEW)){
            keyOrUrl = object.getString(MenuJsonKey.BUTTON_URL);
            if (StringUtils.isEmpty(keyOrUrl)){
                return false;
            }
            stairButton.setUrl(keyOrUrl);
        }
        stairButton.setName(name);
        stairButton.setType(type);
        //二级菜单
        JSONArray sub_button = object.getJSONArray(MenuJsonKey.SUB_BUTTON);
        if (StringUtils.isEmpty(sub_button)){
            return true;
        }else if (sub_button.size() > CommentEnum.FIVE.getCode()){
            return false;
        }
        for (int sub_index = CommentEnum.ZERO.getCode() ; sub_index < sub_button.size() ; sub_index++ ){
            boolean menusType = createMenus(subButtonList, sub_button, sub_index);
            if (!menusType){
                return menusType;
            }
        }
        //一级菜单设置二级菜单
        stairButton.setSubButtons(subButtonList);
        return true;
    }

    /**
     * 二级菜单封装
     * */
    private boolean createMenus(List<WxMenuButton> wxMenuButtonList,
                             JSONArray sub_button,
                             Integer sub_index){
        //二级菜单按钮
        WxMenuButton menu = new WxMenuButton();
        JSONObject buttonJSONObject = sub_button.getJSONObject(sub_index);
        String sub_name = buttonJSONObject.getString(MenuJsonKey.BUTTON_NAME);
        String sub_type = buttonJSONObject.getString(MenuJsonKey.BUTTON_TYPE);
        String sub_keyOrUrl = "";
        if (sub_type.equals(WxConsts.MenuButtonType.VIEW)) {
            sub_keyOrUrl = buttonJSONObject.getString(MenuJsonKey.BUTTON_URL);
            if (StringUtils.isEmpty(sub_keyOrUrl)){
                return false;
            }
            menu.setUrl(sub_keyOrUrl);
        }else if (sub_type.equals(WxConsts.MenuButtonType.CLICK)){
            sub_keyOrUrl = buttonJSONObject.getString(MenuJsonKey.BUTTON_KEY);
            if (StringUtils.isEmpty(sub_keyOrUrl)){
                return false;
            }
            menu.setKey(sub_keyOrUrl);
        }
        menu.setName(sub_name);
        menu.setType(sub_type);
        //二级菜单设置
        wxMenuButtonList.add(menu);
        return true;
    }



}